package com.bn.userprofile;

import java.io.IOException;

import javax.servlet.ServletException;

import atg.core.util.StringUtils;
import atg.droplet.DropletException;
import atg.droplet.DropletFormException;
import atg.projects.store.profile.StorePropertyManager;
import atg.repository.MutableRepositoryItem;
import atg.repository.RepositoryException;
import atg.repository.RepositoryItem;
import atg.servlet.DynamoHttpServletRequest;
import atg.servlet.DynamoHttpServletResponse;
import atg.userprofiling.ForgotPasswordHandler;

public class BNForgotPasswordHandler extends ForgotPasswordHandler {

	private static final String SECURITY_QUESTION = "securityQuestion";
	private static final String NO_USER_FOUND = "InvalidUserForEmail";
	private static final String FORGOT_PASS_OPTION = "forgotPasswordOption";
	private static final String FORGOT_PASS_OPTION_EMAIL = "email";
	private static final String FORGOT_PASS_OPTION_RESET = "reset";
	private static final String MISSING_EMAIL = "missingEmailField";
	private static final String SUCCESSURL = "successURL";
	private static final String SECURITY_ANSWER = "securityAnswer";
	private static final String EMAIL_PARAM = "emailParam";
	private static final String RE_ENTER_PWD = "reEnterPassword";
	private static final String MISMATCHPWD = "pwdDoesntMatch";

	private String verifySuccessURL;
	private String verifyErrorURL;
	private String resetPasswordSuccessURL;
	private String resetPasswordErrorURL;

	@Override
	protected void preForgotPassword(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {
		StorePropertyManager storePropertyManager = (StorePropertyManager) getProfileTools()
				.getPropertyManager();
		String email = (storePropertyManager.getEmailAddressPropertyName());
		String emailValue = (String) getValue().get(email);
		if (StringUtils.isEmpty(emailValue)) {
			String msg = formatUserMessage(MISSING_EMAIL, pRequest);
			String path = generatePropertyPath(FORGOT_PASS_OPTION_EMAIL);
			addFormException(new DropletException(msg, path));
		}
		super.preForgotPassword(pRequest, pResponse);
	}

	@Override
	public boolean handleForgotPassword(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {

		String forgotPassOption = (String) getValue().get(FORGOT_PASS_OPTION);
		if (forgotPassOption.equals(FORGOT_PASS_OPTION_EMAIL)) {
			setForgotPasswordSuccessURL(pRequest.getParameter(SUCCESSURL));
			super.handleForgotPassword(pRequest, pResponse);
		} else {
			StorePropertyManager storePropertyManager = (StorePropertyManager) getProfileTools()
					.getPropertyManager();
			String email = (storePropertyManager.getEmailAddressPropertyName());
			String emailValue = (String) getValue().get(email);

			RepositoryItem profileItem = getProfileTools().getItemFromEmail(
					emailValue);
			if (profileItem != null) {
				String securityQuestion = (String) profileItem
						.getPropertyValue(SECURITY_QUESTION);
				getValue().put(SECURITY_QUESTION, securityQuestion);
			} else {
				String msg = formatUserMessage(NO_USER_FOUND, pRequest);
				String path = generatePropertyPath(storePropertyManager
						.getEmailAddressPropertyName());
				addFormException(new DropletFormException(msg, path));
			}
		}
		checkFormRedirect(getForgotPasswordSuccessURL(),
				getForgotPasswordErrorURL(), pRequest, pResponse);
		return true;
	}

	public void handleVerifyUserDetails(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {
		StorePropertyManager storePropertyManager = (StorePropertyManager) getProfileTools()
				.getPropertyManager();
		String email = (storePropertyManager.getEmailAddressPropertyName());
		String emailValue = (String) getValue().get(email);

		String answer = (String) getValue().get(SECURITY_ANSWER);

		RepositoryItem profileItem = getProfileTools().getItemFromEmail(
				emailValue);
		if (profileItem != null) {
			String securityAnswer = (String) profileItem
					.getPropertyValue(SECURITY_ANSWER);
			String profileEmail = (String) profileItem
					.getPropertyValue(FORGOT_PASS_OPTION_EMAIL);
			if (securityAnswer.equalsIgnoreCase(answer)
					&& profileEmail.equalsIgnoreCase(emailValue)) {
				checkFormRedirect(getVerifySuccessURL(), getVerifyErrorURL(),
						pRequest, pResponse);
			} else {
				String msg = formatUserMessage(NO_USER_FOUND, pRequest);
				String path = generatePropertyPath(storePropertyManager
						.getEmailAddressPropertyName());
				addFormException(new DropletFormException(msg, path));
			}
		}
		checkFormRedirect(getVerifySuccessURL(), getVerifyErrorURL(), pRequest,
				pResponse);
	}

	public void handleResetPassword(DynamoHttpServletRequest pRequest,
			DynamoHttpServletResponse pResponse) throws ServletException,
			IOException {
		StorePropertyManager storePropertyManager = (StorePropertyManager) getProfileTools()
				.getPropertyManager();
		String email = (storePropertyManager.getEmailAddressPropertyName());
		String emailValue = (String) getValue().get(email);
		String password = (storePropertyManager.getPasswordPropertyName());
		String passwordVal = (String) getValue().get(password);
		String reEnterPwd = getStringValueProperty(RE_ENTER_PWD);

		if (!getStringValueProperty(storePropertyManager.getPasswordPropertyName()).equalsIgnoreCase(getStringValueProperty(RE_ENTER_PWD)))
		 {
			String msg = formatUserMessage(MISMATCHPWD, pRequest);
			String path = generatePropertyPath(storePropertyManager
					.getPasswordPropertyName());
			addFormException(new DropletFormException(msg, path));
		} else {

			RepositoryItem profileItem = getProfileTools().getItemFromEmail(
					emailValue);
			if (profileItem != null) {
				MutableRepositoryItem mutableRepositoryItem = (MutableRepositoryItem) profileItem;
				String login = (String)mutableRepositoryItem.getPropertyValue(storePropertyManager.getLoginPropertyName());
				String salt = login;
				salt = getProfileTools().passwordSaltForLogin(login);
				mutableRepositoryItem.setPropertyValue(password, storePropertyManager.generatePassword(salt, password));

				try {
					getProfileTools().getProfileRepository().updateItem(
							mutableRepositoryItem);
				} catch (RepositoryException e) {
					if (isLoggingError()) {
						logError("Error while updating Password : ", e);
					}
				}
			}
		}
		checkFormRedirect(getResetPasswordSuccessURL(), getResetPasswordErrorURL(), pRequest, pResponse);

	}

	public String getResetPasswordSuccessURL() {
		return resetPasswordSuccessURL;
	}

	public void setResetPasswordSuccessURL(String resetPasswordSuccessURL) {
		this.resetPasswordSuccessURL = resetPasswordSuccessURL;
	}

	public String getResetPasswordErrorURL() {
		return resetPasswordErrorURL;
	}

	public void setResetPasswordErrorURL(String resetPasswordErrorURL) {
		this.resetPasswordErrorURL = resetPasswordErrorURL;
	}

	public String getVerifySuccessURL() {
		return verifySuccessURL;
	}

	public void setVerifySuccessURL(String verifySuccessURL) {
		this.verifySuccessURL = verifySuccessURL;
	}

	public String getVerifyErrorURL() {
		return verifyErrorURL;
	}

	public void setVerifyErrorURL(String verifyErrorURL) {
		this.verifyErrorURL = verifyErrorURL;
	}

}
